package com.hyd.tweet.twitter.command;

import com.hyd.tweet.twitter.StatusFormatter;
import com.hyd.tweet.util.StringUtils;
import twitter4j.DirectMessage;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.TwitterException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 获取最新推文
 *
 * @author yiding.he
 */
public class UpdateCommand extends Command {

    @Override
    public boolean showErrorsToUser() {
        return false;
    }

    @Override
    protected List<String> processCommand() throws TwitterException {
        List<String> result = new ArrayList<String>();
        result.addAll(checkTimelineStatuses());
        result.add(checkAtmeStatues());
        result.add(checkDirectMessages());
        return result;
    }

    private String checkDirectMessages() throws TwitterException {
        ResponseList<DirectMessage> directMessages = twitter.getDirectMessages();

        int newMessageCount = 0;
        long latestMessageId = 0;

        for (DirectMessage message : directMessages) {
            if (message.getId() > latestMessageId) {
                latestMessageId = message.getId();
            }

            if (user.getLastDirectMessageId() == null || message.getId() > user.getLastDirectMessageId()) {
                newMessageCount++;
            }
        }

        user.setLastDirectMessageId(latestMessageId);

        if (newMessageCount > 0) {
            return "——有" + newMessageCount + "条新的私信，发送命令\"/ls msg\"查看。";
        } else {
            return "";
        }
    }

    private String checkAtmeStatues() throws TwitterException {
        ResponseList<Status> mentions = twitter.getMentions();

        int newMentionCount = 0;
        long latestMentionId = 0;

        for (Status mention : mentions) {
            if (mention.getId() > latestMentionId) {
                latestMentionId = mention.getId();
            }

            if (user.getLastAtmeStatusId() == null || mention.getId() > user.getLastAtmeStatusId()) {
                newMentionCount++;
            }
        }

        user.setLastAtmeStatusId(latestMentionId);

        if (newMentionCount > 0) {
            return "——有" + newMentionCount + "条新的推文@您，发送命令\"/atme " + newMentionCount + "\"查看。";
        } else {
            return "";
        }
    }

    private List<String> checkTimelineStatuses() throws TwitterException {

        // 如果距离上次更新时间未超过指定的刷新周期则下次再更新
        boolean notReady = System.currentTimeMillis() - user.getLastUpdate() < user.getUpdateInterval() * 60 * 1000;
        if (notReady && arguments.size() > 0) {
            return Collections.emptyList();
        }

        Long since = user.getLastTimelineStatusId();
        since = since == null ? 1 : since;
        if (since == 0) {
            since = 1L;
        }

        Paging paging = new Paging(1, 50, since);

        List<Status> statuses = twitter.getHomeTimeline(paging);

        // 返回的顺序是倒排的，根据聊天习惯，改为顺排
        Collections.reverse(statuses);

        long biggest = since;
        List<String> timelineStatuses = new ArrayList<String>();
        for (Status status : statuses) {
            if (since >= status.getId()) {
                continue;
            }

            int rollerId = user.pushToRoller(status);
            String tweetStr = StatusFormatter.formatStatus(twitterUser, status, rollerId);

            timelineStatuses.add(tweetStr);

            if (biggest < status.getId()) {
                biggest = status.getId();
            }
        }

        String date = StringUtils.now(twitterUser, "HH:mm");

        if (timelineStatuses.isEmpty()) {
            timelineStatuses.add("——没有新推(" + date + ")。");
        } else {
            user.setLastTimelineStatusId(biggest);
            timelineStatuses.add("——已列出" + timelineStatuses.size() + "条新推(" + date + ")。");
        }

        user.setLastUpdate(System.currentTimeMillis());
        return timelineStatuses;
    }

}
